from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from django.utils.decorators import method_decorator
from django.core.exceptions import ValidationError

# Create your views here.


def login_decorator(func):
    def wrapper(request, *args, **kwargs):
        print(request.path)
        print(request.get_full_path())
        print(request.path_info)
        target_url = request.get_full_path()
        ret = redirect('/login/?next=%s' % target_url)
        if request.COOKIES.get('username') == 'AKW':
            ret = func(request, *args, **kwargs)
        return ret
    return wrapper


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 获取用户上一次想要访问的url
        target_url = request.GET.get('next', '/home/')
        if username == 'AKW' and password == 'FW249746':
            obj = redirect(target_url)
            obj.set_cookie('username', username, max_age=5)  # 5秒过期
            return obj
    return render(request, 'login.html')


@login_decorator
def home(request):
    return HttpResponse('我是home页面, 只有登录的用户才能进来')


@login_decorator
def func(request):
    return HttpResponse('这是function页面')


@login_decorator
def logout(request):
    obj = redirect('/login/')
    obj.delete_cookie('username')
    return obj


def set_session(request):
    # 设置session过期时间

    request.session['hobby'] = 'girl'
    # request.session.set_expiry(0)
    request.session['hobby1'] = 'girl1'
    request.session['hobby2'] = 'girl2'
    request.session['hobby3'] = 'girl3'
    print(request.session)
    print(request.session.get('hobby'))
    print(request.session.get('hobby1'))
    print(request.session.get('hobby2'))
    print(request.session.get('hobby3'))
    print(request.COOKIES)
    return HttpResponse('嘿嘿嘿')


def get_session(request):
    if request.session.get('hobby'):
        print(request.session.get('hobby'))
        return HttpResponse('哈哈哈')
    return HttpResponse('打野 关门了 明晚再来吧')


def del_session(request):
    request.session.delete()
    return HttpResponse('删喽')


@method_decorator(login_decorator, name='get')  # 针对不同的方法添加不同的装饰器
@method_decorator(login_decorator, name='post')
class MyLogin(View):
    @method_decorator(login_decorator)  # 方法3 他会直接作用域当前类里面所有的方法
    def dispatch(self, request, *args, **kwargs):
        pass

    # @method_decorator(login_decorator)  # 方式一
    def get(self, request):
        return HttpResponse('get请求')

    def post(self, request):
        return HttpResponse